package com.wbcs.system.component.application.report;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import org.apache.poi.ss.usermodel.Workbook;

import com.jf.render.TemplateRender;
import com.wbcs.config.Config;
import com.wbcs.config.component.IComponentConfigBean;
import com.wbcs.config.component.application.report.ColBean;
import com.wbcs.config.component.application.report.ConditionBean;
import com.wbcs.config.component.application.report.ReportBean;
import com.wbcs.config.component.other.JavascriptFileBean;
import com.wbcs.system.CacheDataBean;
import com.wbcs.system.ReportRequest;
import com.wbcs.system.assistant.ReportAssistant;
import com.wbcs.system.component.application.report.abstractreport.AbsListReportType;
import com.wbcs.system.component.application.report.abstractreport.AbsReportType;
import com.wbcs.system.component.container.AbsContainerType;
import com.wbcs.util.Consts;
import com.wbcs.util.Consts_Private;
import com.wbcs.util.Tools;

public class JfGridReportType extends AbsListReportType{

	private AbsContainerType parentContainerType;
	private IComponentConfigBean reportBean;
	private ReportRequest rrquest;
	
	public JfGridReportType(AbsContainerType parentContainerType, IComponentConfigBean comCfgBean,
			ReportRequest rrequest) {
		super(parentContainerType, comCfgBean, rrequest);
		this.parentContainerType = parentContainerType;
		this.reportBean = comCfgBean;
		this.rrequest = rrequest;
	}
	public void loadReportData(boolean shouldInvokePostaction){
		ReportBean rBean = (ReportBean) reportBean;
		CacheDataBean cdb = this.rrequest.getCdb(rBean.getId());
		String pageno = this.rrequest.getRequest().getParameter(rBean.getId()+"_PAGENO");
		try{
			if(pageno != null && !"".equals(pageno)){
				cdb.setPageno(Integer.parseInt(pageno));
			}
		}catch(Exception e){
		}
		super.loadReportData(shouldInvokePostaction);
		
	}
	@Override
	public String showReportData() {
		ReportBean rBean = (ReportBean) reportBean;
		StringBuilder sb = new StringBuilder();
		String jfgrid = Config.getInstance().getResourceString(null,null,"${jfgrid.table.default}",false);
		jfgrid = Tools.replaceAll(jfgrid, "%PAGEID%", rBean.getPageBean().getId());
		jfgrid = Tools.replaceAll(jfgrid, "%REPORTID%", rBean.getId());
		jfgrid = Tools.replaceAll(jfgrid, "%header%", getHeader(rBean));
		jfgrid = Tools.replaceAll(jfgrid, "%table%", getTable(rBean));
		jfgrid = Tools.replaceAll(jfgrid, "%pagination%", getPagination(rBean));
		sb.append(jfgrid);
		
		sb.append("<script src='"+Config.webroot+"webresources/jsplugins/vue/vue.min.js"+"'></script>");
		sb.append("<script src='"+Config.webroot+"webresources/script/wbcs_vue_system.js"+"'></script>");
		return sb.toString();
	}
	/**
	 * 获取表头
	 * @return
	 */
	public String getHeader(ReportBean rBean){
		String rowselect = this.alrbean.getRowSelectType();
		StringBuffer sb = new StringBuffer("<template><el-table ");
		//基本属性、事件
		sb.append("stripe ");
		sb.append(":data='tableData' ");
		sb.append("style='width: 100%' ");
		if(rowselect != null && Consts.ROWSELECT_SINGLE.equals(rowselect.trim())){
			sb.append("ref='singleTable' ");
			sb.append("highlight-current-row ");
			sb.append("@current-change='singleRowChange'>");
		}else if(rowselect != null && (Consts.ROWSELECT_MULTIPLY.equals(rowselect.trim()))){
			sb.append("ref='multipleTable' ");
			sb.append("@selection-change='multiplyRowChange'>");
			sb.append("<el-table-column type='selection' width='55'></el-table-column>");
		}else{
			sb.append(">");
		}
		List<ColBean> list = rBean.getDbean().getLstCols();
		for (ColBean colBean : list) {
			sb.append("<el-table-column ");
			//sb.append("prop='"+colBean.getColumn()+"' ");
			sb.append("label='"+colBean.getLabel()+"' ");
			sb.append("width='"+colBean.getWidth()+"' >");
			sb.append("<template scope='scope'>");
			sb.append("<el-input size='small' v-model='scope.row."+colBean.getColumn()+"'></el-input>");
			sb.append("<span>{{scope.row."+colBean.getColumn()+"}}</span>");
			sb.append("</template>");
			sb.append("</el-table-column>");
		}
		sb.append("</el-table></template>");
		return sb.toString();
	}
	/**
	 * 获取表体
	 * @return
	 */
	public String getTable(ReportBean rBean){
		AbsReportType reportTypeObj = rrequest.getDisplayReportTypeObj(rBean.getId());
        List<Object> dataList = reportTypeObj.getLstReportData();
        List<ColBean> colList = rBean.getDbean().getLstCols();
		StringBuffer sb = new StringBuffer("var dataTableObject={data(){return {tableData:[");
		if(dataList != null && dataList.size() > 0){
        	for(int i=0;i<dataList.size();i++){
        		Object rowDataObj = dataList.get(i);
        		sb.append(i == 0?"{":",{");
        		for (int j=0;j<colList.size();j++) {
        			sb.append(j == 0?"":",");
        			sb.append(colList.get(j).getColumn()+":'"+ReportAssistant.getInstance().getPropertyValue(rowDataObj,colList.get(j).getColumn())+"'");
        		}
        		sb.append("}");
        	}
		}
		sb.append("],currentRow:null,multipleSelection:[]}},");
		//methods
		sb.append("methods:{");
		sb.append("paginationChange(val){var url=location.href;var pageParam='"+rBean.getId()+"_PAGENO';if(url.indexOf(pageParam)<0){location.href=url+(url.indexOf('?')>0?'&':'?')+pageParam+'='+val;}else{var reg=new RegExp(pageParam+'\\=[0-9]*');location.href=url.replace(reg,pageParam+'='+val)}}");
		sb.append(",singleRowChange(val){this.currentRow = val;}");
		sb.append(",multiplyRowChange(val){this.multipleSelection = val;}");
		sb.append("}};");
		sb.append("var Ctor = Vue.extend(dataTableObject);new Ctor().$mount('#"+rBean.getPageBean().getId()+"_guid_"+rBean.getId()+"');");
		
		return sb.toString();
	}
	/**
	 * 获取分页
	 */
	public String getPagination(ReportBean rBean){
		CacheDataBean cdb = this.rrequest.getCdb(rBean.getId());
		StringBuffer sb = new StringBuffer();
		if(cdb.getPagesize() > 0){
			sb.append("<el-pagination background align='center' ");
			//sb.append("small ");
			sb.append("layout='prev, pager, next' ");
			sb.append("@current-change='paginationChange' ");
			sb.append("@prev-click='paginationChange' ");
			sb.append("@next-click='paginationChange' ");
			sb.append(":page-size='"+cdb.getPagesize()+"' ");
			sb.append(":current-page='"+cdb.getRealPageno()+"' ");
			sb.append(":total='"+cdb.getRecordcount()+"' ");
			sb.append("></el-pagination>");
		}
		return sb.toString();
	}
	/**
	 * 模板初始化
	 * @param rbTmp 
	 * @param dynTplPath 
	 */
	public void initJfHtml(final ReportBean rbTmp, String dynTplPath){
		if(rrequest.getRequest().getAttribute(Consts_Private.REPORT_TEMPLATE) != null)return;
		
		/**
		 * 此处需要改造
		 */
		Map<String,Object> sharedObjectMap= null;//TemplateRender.engine.getEngineConfig().getSharedObjectMap();
        if(sharedObjectMap == null){
        	sharedObjectMap = new LinkedHashMap<String, Object>();
        }
        //table模板化
        if(!sharedObjectMap.containsKey(rbTmp.getPageBean().getId())){
        	sharedObjectMap.put(rbTmp.getPageBean().getId(), new LinkedHashMap<String,Object>());
        }
        Map<String,Object> pageMap = (Map<String, Object>) sharedObjectMap.get(rbTmp.getPageBean().getId());
        if(!pageMap.containsKey(rbTmp.getId())){
        	pageMap.put(rbTmp.getId(), new LinkedHashMap<String,Object>());
        }
        Map<String,Object> rptMap = (Map<String, Object>) pageMap.get(rbTmp.getId());
        rptMap.put(Consts_Private.TAGNAME_TABLE, rbTmp.getPageBean().getId()+"."+rbTmp.getId());
        //查询条件模板化
        if(rbTmp.getSbean().getLstConditions().size() > 0){
        	for(ConditionBean cBean : rbTmp.getSbean().getLstConditions()){
            	if(sharedObjectMap.get(rbTmp.getPageBean().getId()) == null){
            		sharedObjectMap.put(rbTmp.getPageBean().getId(), new LinkedHashMap<String,Object>(){{
            			put(rbTmp.getId(), new LinkedHashMap<String,Object>(){{
            				put(Consts_Private.TAGNAME_CONDITION, new LinkedHashMap<String,String>());
            			}});
            		}});
            	}else{
            		Map<String,Map<String,Map<String,String>>> rMap = (Map<String, Map<String, Map<String, String>>>) sharedObjectMap.get(rbTmp.getPageBean().getId());
            		if(!rMap.get(rbTmp.getId()).containsKey(Consts_Private.TAGNAME_CONDITION)){
            			rMap.get(rbTmp.getId()).put(Consts_Private.TAGNAME_CONDITION, new LinkedHashMap<String,String>());
            		}
            	}
            	Map<String,LinkedHashMap<String,LinkedHashMap<String,String>>> rMap = (Map<String, LinkedHashMap<String,LinkedHashMap<String,String>>>) sharedObjectMap.get(rbTmp.getPageBean().getId());
            	rMap.get(rbTmp.getId()).get(Consts_Private.TAGNAME_CONDITION).put(cBean.getName(), rbTmp.getPageBean().getId()+"."+rbTmp.getId()+"."+cBean.getName());
            }
        }
        
		try {
			TemplateRender.engine
				.getTemplate(dynTplPath,rrequest.getRequest(),rrequest.getWResponse().getResponse())
				.render(new HashMap<String,Object>(),rrequest.getWResponse().getResponse().getWriter(),rrequest.getRequest(),rrequest.getWResponse().getResponse());
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	@Override
	public String showReportData(boolean showtype) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public String getColSelectedMetadata() {
		// TODO Auto-generated method stub
		return null;
	}

}
